package com.sxp.servlet;

import com.sxp.bean.Book;
import com.sxp.bean.Cart;
import com.sxp.bean.User;
import com.sxp.dao.BookDao;
import com.sxp.dao.CartDao;
import com.sxp.dao.impl.BookDaoImpl;
import com.sxp.dao.impl.CartDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author hsowan
 * @date 2019-06-14
 **/
@WebServlet("/cart/delete")
public class DeleteCartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int bookId = Integer.parseInt(req.getParameter("bookid"));
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if (user != null) {
            CartDao cartDao = new CartDaoImpl();
            Cart cart = cartDao.getByBookIdAndUserId(bookId, user.getId());
            if (cart != null) {
                if (cart.getAmount() >= 1) {
                    cart.setAmount(cart.getAmount() - 1);
                    cartDao.update(cart);

                    BookDao bookDao = new BookDaoImpl();
                    Book book = bookDao.getById(cart.getBookId());
                    book.setStock(book.getStock() + 1);
                    bookDao.update(book);

                    session.setAttribute("msg", "操作成功！");
                    resp.sendRedirect("/obs/message.jsp");
                } else {
                    session.setAttribute("msg", "信息不存在！");
                    resp.sendRedirect("/obs/message.jsp");
                }
            } else {
                session.setAttribute("msg", "信息不存在！");
                resp.sendRedirect("/obs/message.jsp");
            }
        }else {
            session.setAttribute("msg", "未登录！");
            resp.sendRedirect("/obs/message.jsp");
        }
    }
}
